package cn.wolfcode.luowowo.comment.service;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private IStrategyCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment strategyComment) {
            strategyComment.setCreateTime(new Date());
        repository.save(strategyComment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        Query query = new Query();
        //设置条件
        if (qo.getDetailId()!=-1){
             query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //totalPage
        long total = template.count(query, StrategyComment.class);
        //pageSize
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        query.with(pageable);
        if (total ==0){
            Page.empty();
        }
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,total);
    }


    /**
     * 点赞
     * @param toid
     * @param fromid
     */
    @Override
    public void commentThumbUp(String toid, Long fromid) {
        //判断当前用户是点赞还是取消点赞
        Optional<StrategyComment> ol = repository.findById(toid);
        StrategyComment comment = ol.get();
        if (comment==null){
            return;
        }
        List<Long> thumbuplist = comment.getThumbuplist();
        if (!thumbuplist.contains(fromid)){
            //点赞加1
            comment.setThumbupnum(comment.getThumbupnum()+1);
            thumbuplist.add(fromid);
        }else {
            //点赞减1
            comment.setThumbupnum(comment.getThumbupnum()-1);
            thumbuplist.remove(fromid);
        }
        repository.save(comment);

    }
}
